package com.htc.dlc.fragment;

import java.io.File;

import com.htc.common.ActionEvent;
import com.htc.constants.Constants;
import com.htc.controller.AboutsController;
import com.htc.dlc.R;
import com.htc.dlc.SettingsActivity;
import com.htc.model.dto.AboutsDTO;
import com.htc.webservice.PicassoUtils;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.widget.ImageView;
import android.widget.TextView;

public class FragmentAboutGrace extends Fragment {
	private TextView title_grace;
	private ImageView img_grace;
	private WebView webView_description_grace;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		View rootView = inflater.inflate(R.layout.fragment_about_grace,
				container, false);
		title_grace = (TextView) rootView.findViewById(R.id.title_grace);
		img_grace = (ImageView) rootView.findViewById(R.id.img_grace);
		webView_description_grace = (WebView) rootView
				.findViewById(R.id.webView_description_grace);
		initData();
		return rootView;
	}

	public void initData() {
		ActionEvent e = new ActionEvent(this, Constants.GET_ABOUT_GRACE, null,
				null);
		AboutsController.getInstance().handleViewEvent(e);
	}

	public void handleControllerViewEvent(ActionEvent e) {
		AboutsDTO dto = (AboutsDTO) e.viewData;
		SettingsActivity st = new SettingsActivity();
		String encoding = "utf-8";
		this.webView_description_grace.getSettings().setJavaScriptEnabled(true);
		if (st.flag == 0) {
			this.title_grace.setText(dto.getCategoryTitle());
			this.webView_description_grace.loadDataWithBaseURL(null,
					dto.getCategoryDescription(), null, encoding, null);
		} else if (st.flag == 1) {
			this.title_grace.setText(dto.getCategoryTitleAr());
			this.webView_description_grace.loadDataWithBaseURL(null,
					dto.getCategoryDescriptionAr(), null, encoding, null);
		}

		String path = dto.getAbout_us_category_image();
		String currentUrl = Constants.URL_IMAGE_PAHT + path;
		
		if(path != null){
			String[] strs = path.split("/");
			File f = new File(Environment.getExternalStorageDirectory() + "/"
					+ Constants.APP_NAME + "/" + strs[0] + "/" + strs[1]);
			if (f.exists()) {
				Bitmap bmp = BitmapFactory.decodeFile(f.getAbsolutePath());
				img_grace.setImageBitmap(bmp);
			} else {
				PicassoUtils.getInstance().showImageFromUrl(getActivity(),
						currentUrl, R.drawable.bgday, img_grace);
				// TODO: create folder?

				PicassoUtils.getInstance().saveImageFromUrl(
						getActivity().getApplicationContext(), currentUrl, strs[1],
						strs[0]);
			}
		}
		

	}

}